package org.glorylight.hacks.social.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.SerializationUtils;
import org.glorylight.hacks.social.data.MessageData;
import org.glorylight.hacks.social.data.MessageThread;
import org.glorylight.hacks.social.data.Messages;
import org.glorylight.hacks.social.service.MessageService;
import org.glorylight.hacks.social.util.UUIDHelper;
import org.infinispan.manager.EmbeddedCacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.sun.jersey.api.representation.Form;


@Component
@Scope("prototype")
@Path("/messages")
public class MessageController extends AbstractBaseController {

	private final static Logger log = LoggerFactory.getLogger(MessageController.class);
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private EmbeddedCacheManager cacheManager;
	
	/*
	 * Get all message
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Messages getMesssages() {
		List<MessageThread> threads = constructMessages(getActiveLogin());
//		Cache<String, List<MessageThread>> cacheManager.getCache();
		List<MessageThread> destination = new ArrayList<MessageThread>(threads.size());
		for(MessageThread messageThread : threads)
			destination.add(SerializationUtils.clone(messageThread));
		for(MessageThread t : destination)
			t.clearMessages();
		
//		return new Messages(destination);
		return new Messages(threads);
	}
	
	/*
	 * Send Message
	 */
	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Path("/message")
	public Response sendMesssage(Form data) {
		String senderId = getActiveLogin();
		MessageData messageData = new MessageData(UUID.randomUUID(), senderId, 
				 data.getFirst("recipientId", String.class), data.getFirst("subject", String.class), 
				new Date(), data.getFirst("content", String.class), true);
		try {
			messageService.addMessage(messageData);
		} catch (Exception e){
			log.error("error persisting message", e);
			Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
		}
		return Response.status(Response.Status.ACCEPTED).build();
	}

	/*
	 * Get Message by id
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path("/message/{messageId}")
	public Messages getMesssagesThread(@PathParam("messageId") String messageId) {
		List<MessageThread> threads = new ArrayList<MessageThread>();
//		threads.add(userProfile.getThreadMessage(messageId));
		return new Messages(threads);
	}
	
	private List<MessageThread> constructMessages(String userName) {
		Map<String, List<MessageData>> datas = messageService.findAllByUserPerThread(userName);
		List<MessageThread> threads = new ArrayList<MessageThread>();
		MessageThread mt = null;
		for (Entry<String, List<MessageData>> data : datas.entrySet()) {
			mt = new MessageThread(UUIDHelper.uuidToString(UUID.randomUUID()), data.getKey(), data.getValue());
			for (MessageData msgDt : data.getValue())
				mt.getParticipants().add(msgDt.getSender());
//			userProfile.addThreadMessage(mt);
			threads.add(mt);
		}
		return threads;
	}
}